import { v4 } from "uuid"

function delay(ms) {
  return new Promise(resolve =>
    setTimeout(resolve, ms)
  )
}

const todos = []

export async function addTodo(text) {
  await delay(500)
  const todo = {
    id: v4(),
    text,
    completed: false
  }
  todos.push(todo)
  return todo
}

export async function fetchTodos(filter) {
  await delay(500)
  switch(filter) {
    case 'all':
      return todos.slice()
    case 'active':
      return todos.filter(todo => !todo.completed)
    case 'completed':
      return todos.filter(todo => todo.completed)
    default:
      throw new Error('无效filter')
  }
}